<?php
declare(strict_types=1);
namespace app\admin\controller;
// 角色分组
class AdminGroup extends Base
{
    protected string $model = 'admin_group';
    protected string $order = 'id ASC';
    protected string $fieldExcept = 'auth_menu,auth_node'; // 排除字段
    protected  int $formSearch = 0;

    // 更新字段预设条件
    protected function _multi_where(string $field, $value): array
    {
        return $field == 'status' ? [['id<>1']] : []; // 不允许修改超级管理员的status
    }

    // 设置权限
    public function node(int $id, array $req)
    {
        return $this->edit($id, $req);
    }

    // 获取菜单权限api
    public function api_auth_menu(string $selected = '')
    {
        $selected = !empty($selected) ? array_map('intval', explode(',', $selected)) : [];
        $data = db('menu')->field('id,pid,title')->where('id>1 AND status=1')->order('sort ASC,id ASC')->select();
        $data = $this->_get_tree($data, 1, $selected);
        $this->_json(200, '', $data);
    }

    private function _get_tree(array $menu, int $pid = 1, array $selected = []): array
    {
        $tree = [];
        foreach ($menu as $v) {
            $v['checked'] = in_array($v['id'], $selected) || $v['id'] == 2;
            $v['disabled'] = false;
            if ($v['pid'] == $pid) {
                $v['children'] = $this->_get_tree($menu, $v['id'], $selected);
                $tree[] = $v;
            }
        }
        return $tree;
    }

    // 获取节点权限api
    public function api_auth_node(string $selected = '')
    {
        $menu = db('auth')->field('id,title,controller')->where('status=1')->order('sort ASC,id ASC')->select();
        $data = [];
        $i = 1;
        foreach ($menu as $vo) {
            $data[$i]['node_id'] = '-'.$vo['id'];
            $data[$i]['name'] = $vo['title'];
            $data[$i]['alias'] = $vo['controller'];
            $data[$i]['palias'] = '0';
            $children = $this->_get_children($vo['id']);
            if (!empty($children)) {
                $data = array_merge($data, $children);
                $i = count($data);
            }
            $i ++;
        }
        $selected = explode(',', $selected);
        $this->_json(200, '', ['list' => $data, 'checkedAlias' => $selected]);
    }

    private function _get_children(int $pid): array
    {
        $data = [];
        $tmp = db('auth_node')->field('id,title,controller,method')->where('auth_id', $pid)->where('status=1')->order('sort ASC,id ASC')->select();
        foreach ($tmp as $k => $v) {
            $data[$k]['node_id'] = ''.$v['id'];
            $data[$k]['name'] = $v['title'];
            $data[$k]['alias'] = $v['controller'].'-'.$v['method'];
            $data[$k]['palias'] = $v['controller'];
        }
        return $data;
    }

}